const Base = require("./base.js");

module.exports = class extends Base {
  /**
   * 列表
   * @param name
   * @param cate_id
   * @param pageNum
   * @param pageSize
   * @returns {Promise<any>}
   */
  async indexAction() {
    const sT = Date.now();
    const post = this.post();
    const db = this.model("wiki");
    let result = {};
    result.errno = 0;
    result.data = await db.list(post);
    result.time = Date.now() - sT;
    return this.json(this.format(result));
  }

  /**
   * 删除
   * @param id
   * @returns {Promise<void>}
   */
  async delAction() {
    const post = this.post();
    const sT = Date.now();
    const db = this.model("wiki");
    const dbContent = this.model("wiki_meta");
    let result = {};
    try {
      await db.delete(post.id);
      await dbContent.where({ wiki_id: post.id }).delete();
      result.errno = 0;
    } catch (e) {
      result.errno = -1;
      result.errmsg = e.toString();
    }
    result.time = Date.now() - sT;
    return this.json(this.format(result));
  }

  /**
   * 添加
   * @returns {Promise<any>}
   */
  async addAction() {
    const sT = Date.now();
    const post = this.post();
    let result = {};
    try {
      result.data = await this.save(post);
      result.errno = 0;
    } catch (e) {
      result.errno = -1;
      result.errmsg = e.toString();
    }
    result.time = Date.now() - sT;
    return this.json(this.format(result));
  }

  /**
   * 详情
   * @returns {Promise<any>}
   */
  async detailAction() {
    const sT = Date.now();
    const post = this.post();
    const db = this.model("wiki");
    let result = {};
    try {
      result.errno = 0;
      result.data = await db.detail(post.id);
    } catch (e) {
      result.errno = -1;
      result.errmsg = e.toString();
    }
    result.time = Date.now() - sT;
    return this.json(this.format(result));
  }

  /**
   * 修改
   * @returns {Promise<any>}
   */
  async updateAction() {
    const sT = Date.now();
    const post = this.post();
    let result = {};
    try {
      result.data = await this.save(post);
      result.errno = 0;
    } catch (e) {
      result.errno = -1;
      result.errmsg = e.toString();
    }
    result.time = Date.now() - sT;
    return this.json(this.format(result));
  }

  async save({ ...form }) {
    const db = this.model("wiki");
    const dbContent = this.model("wiki_meta");
    const id = await db.save({ ...form });
    if (!form.id) form.id = id;
    await dbContent.save({ wiki_id: form.id, ...form });
    return form.id;
  }
};
